package com.git.hui.yinshua.common.alarm;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.git.hui.yinshua.common.AsyncUtil;
import com.git.hui.yinshua.common.email.EmailWrapper;

/**
 * 报警
 *
 * @author yihui
 * @date 2024/06/07
 */
public class ServiceAlarm extends AppenderBase<ILoggingEvent> {
    private static final long INTERVAL = 10 * 1000 * 60;
    private long lastAlarmTime = 0;

    @Override
    protected void append(ILoggingEvent iLoggingEvent) {
        if (canAlarm()) {
            // 异步发送报警记录，避免阻塞业务流程
            AsyncUtil.execute(() -> doAlarm(iLoggingEvent.getFormattedMessage()));
        }
    }

    private boolean canAlarm() {
        long now = System.currentTimeMillis();
        if (now - lastAlarmTime >= INTERVAL) {
            lastAlarmTime = now;
            return true;
        } else {
            return false;
        }
    }

    private void doAlarm(String content) {
        try {
            EmailWrapper.sendMail("异常报警", "bangzewu@126.com", content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
